<!-- 基础数据列表 -->
<script setup lang="ts">
import type { BSTableData, PageTableRequestData } from "@@/apis/basic-data/types"
import { deleteStructField, deleteStructFieldBatch, searchStructDataApi } from "@@/apis/basic-data"
import Card from "@@/components/CardItem/card.vue"
import { usePagination } from "@@/composables/usePagination"
import { parseSearchDate } from "@@/utils/datetime"
import { Refresh, Search } from "@element-plus/icons-vue"
import { ElMessage, ElMessageBox } from "element-plus"
import { computed, nextTick, reactive, ref } from "vue"
import { useRouter } from "vue-router"
import { useAutoRefresh } from '@/layouts/composables/useAutoRefresh'
import XEUtils from "xe-utils"
import { dataTypeTextMap } from "@@/constants/other-keys"

defineOptions({
  // 命名当前组件
  name: "BasicDataIndex"
})

interface ExtendedBasicData extends Omit<BSTableData, "createTime"> {
  isSelected?: boolean
  time_range?: string[]
  createTime?: string
}

interface SearchParams extends PageTableRequestData {
  time_range?: string[]
}

const router = useRouter()
const isGrid = ref<boolean>(true)
const searchFormRef = ref()
const searchMore = ref<boolean>(false)
const loading = ref<boolean>(false)
const tableData = ref<ExtendedBasicData[]>([])
const multipleSelection = ref<ExtendedBasicData[]>([])
const tableRef = ref()

const { paginationData, handleSizeChange, handleCurrentChange } = usePagination()

const searchData = reactive<SearchParams>({
  code: "",
  type: "",
  current_page: 1,
  size: 20,
  searchKey: "",
  time_range: undefined,
  create_time: undefined,
  end_time: undefined,
  name: "",
  description: "",
  country: ""
})

// 重置搜索
function resetSearch() {
  searchFormRef.value?.resetFields()
}

function handleSearchMore() {
  searchMore.value = !searchMore.value
  if (!searchMore.value) {
    resetSearch()
  }
}

function getTableData() {
  loading.value = true
  const params: PageTableRequestData = {
    size: paginationData.pageSize,
    current_page: paginationData.currentPage,
    code: searchData.code || "",
    type: "",
    searchKey: searchData.searchKey || "",
    create_time: searchData.create_time,
    end_time: searchData.end_time,
    name: searchData.name,
    description: searchData.description,
    country: searchData.country
  }

  if (searchMore.value && searchData.time_range && searchData.time_range.length == 2) {
    params.create_time = searchData.time_range[0]
    params.end_time = parseSearchDate(searchData.time_range[1])
  }
  searchStructDataApi(params)
    .then(({ data }) => {
      tableData.value = data.rows
      paginationData.total = data.total
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
useAutoRefresh(getTableData)

// 查询
function handleSearch() {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}

function handleMultipleDelete() {
  const ids: string[] = []
  const names: string[] = []
  multipleSelection.value.forEach((item: any) => {
    ids.push(item.id as string)
    names.push(item.name as string)
  })
  ElMessageBox.confirm(`正在删除基础数据：${names.join("，")}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteStructFieldBatch(ids).then(() => {
      ElMessage.success("删除成功")
      hanldeClearSelection()
      getTableData()
    }).catch(() => {
      ElMessage.error("删除失败")
    })
  })
}

function handleSelectionChange(val: any) {
  multipleSelection.value = val
}

function hanldeClearSelection() {
  nextTick(() => {
    tableRef.value.clearSelection()
  })
}

function getRowKeys(row: any) {
  return row.id
}

// #region 删
function handleDelete(row: any) {
  ElMessageBox.confirm(`正在删除基础数据：${row.name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteStructField(row.id).then(() => {
      ElMessage.success("删除成功")
      hanldeClearSelection()
      getTableData()
    }).catch(() => {
      ElMessage.error("删除失败")
    })
  })
}
// #endregion
// #region 详情
function handleView(row: ExtendedBasicData) {
  router.replace({ name: "BasicDataView", query: { id: row.id } })
}
// #endregion
function handleToggleSelect(row: any) {
  tableRef.value?.toggleRowSelection(row, undefined, false)
}

// 新建
function handleCreateTask(type: string) {
  router.replace({ name: "BasicDataCreate", query: { type } })
}

const selectedId = computed(() => {
  if (multipleSelection.value?.length > 0) {
    const ids = XEUtils.map(multipleSelection.value, (item: any) => {
      return item.id
    })
    return ids
  }
  return []
})

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container pager-container">
    <div class="cc-search">
      <div class="cc-search-common">
        <el-input v-model="searchData.searchKey" placeholder="请输入搜索内容" class="csc-search-input" @keyup.enter.native="handleSearch">
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>
        <div class="csc-more" @click="handleSearchMore">
          <span>更多</span>
          <el-icon v-if="!searchMore">
            <ArrowDown />
          </el-icon>
          <el-icon v-else>
            <ArrowUp />
          </el-icon>
        </div>
      </div>
      <div class="cc-search-common-more" v-if="searchMore">
        <el-form ref="searchFormRef" :model="searchData" :inline="true" @keyup.enter="handleSearch">
          <el-form-item prop="code" label="名称">
            <el-input v-model="searchData.code" @change="handleSearch()" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="name" label="辅助标识">
            <el-input v-model="searchData.name" @change="handleSearch()" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="time_range" label="时间范围">
            <el-date-picker
              v-model="searchData.time_range"
              type="daterange"
              unlink-panels
              range-separator="至"
              value-format="YYYY-MM-DD"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              @change="handleSearch()"
            />
          </el-form-item>
          <el-form-item>
            <el-button :icon="Refresh" @click="resetSearch">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div v-loading="loading" class="content-other">
      <div class="flex-between mb-main-padding">
        <div class="flex-y-center tag">
          <el-button type="primary" @click="handleCreateTask('class')">
            新建结构体
          </el-button>
          <el-button type="primary" @click="handleCreateTask('enum')">
            新建枚举
          </el-button>
          <el-button
            :disabled="multipleSelection.length < 1" type="danger"
            @click="handleMultipleDelete"
          >
            批量删除
          </el-button>
        </div>
        <div class="flex-y-center sh-operate">
          <div class="sh-btn" :class="{ active: isGrid }" @click="() => isGrid = true">
            <el-tooltip content="卡片" placement="bottom">
              <SvgIcon name="table-grid" />
            </el-tooltip>
          </div>
          <div class="sh-btn" :class="{ active: !isGrid }" @click="() => isGrid = false">
            <el-tooltip content="列表" placement="bottom">
              <SvgIcon name="table-list" />
            </el-tooltip>
          </div>
        </div>
      </div>
      <div v-show="isGrid" class="cpi-content-main">
        <div class="custom-card-container">
          <template v-for="(item, index) in tableData" :key="index">
            <Card
              :tag="dataTypeTextMap[item.type]"
              :is-other="true"
              :name="item.code"
              :create-by="XEUtils.isEmpty(item.name) ? item.code : item.name"
              :create-time="item.updateTime == null ? '' : item.updateTime"
              :description="item.description == null ? '' : item.description"
              :data="item"
              :is-download="false"
              :selected="selectedId.includes(item.id as string)"
              :other-params="{
                createTime: item.createTime,
              }"
              @handle-delete="handleDelete"
              @handle-view="handleView"
              @toggle-select="handleToggleSelect"
            />
          </template>
        </div>
      </div>
      <div v-show="!isGrid" class="cpi-content-main">
        <el-auto-resizer>
          <template #default="{ height, width }">
            <el-table
              ref="tableRef" v-loading="loading" :data="tableData" :row-key="getRowKeys" :width="width"
              :height="height" @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" header-align="left" :reserve-selection="true" width="55" />
              <el-table-column prop="code" label="名称" header-align="left" />
              <el-table-column prop="name" show-overflow-tooltip label="别名" header-align="left" />
              <el-table-column prop="description" show-overflow-tooltip label="描述" header-align="left" />
              <el-table-column prop="updateTime" label="修改时间" header-align="left" :width="180" />
              <el-table-column fixed="right" label="操作" align="center" width="140">
                <template #default="scope">
                  <el-space :size="12">
                    <el-link :underline="false" @click.stop v-throttle="() => handleView(scope.row)" title="查看">
                      <el-icon :size="18">
                        <View />
                      </el-icon>
                    </el-link>
                    <el-link :underline="false" type="danger" @click.stop v-throttle="() => handleDelete(scope.row)" title="删除">
                      <el-icon :size="18">
                        <Delete />
                      </el-icon>
                    </el-link>
                  </el-space>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-auto-resizer>
      </div>
    </div>

    <div class="pager-wrapper">
      <el-pagination
        background
        layout="total, sizes, ->, prev, pager, next, jumper"
        :disabled="loading"
        :page-sizes="paginationData.pageSizes"
        :total="paginationData.total"
        :page-size="paginationData.pageSize"
        :current-page="paginationData.currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>
